/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.spreadsheet.planning;

import cn.ac.nercis.pes.community.component.spreadsheet.TableSheetView;
import cn.ac.nercis.pes.community.model.vo.evaluation.EvaluationRequireVO;
import cn.ac.nercis.pes.community.support.event.EventCallback;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.controlsfx.control.spreadsheet.GridBase;
import org.controlsfx.control.spreadsheet.SpreadsheetCell;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 测评指标确认表控件
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class EvaluationRequireSheetView extends TableSheetView<EvaluationRequireVO> {
    private final static List<String> COLUMNS = List.of("配合工作","需求说明");
    private final static Integer PROJECT_COLUMN_INDEX = 0;
    private final static Integer DESC_COLUMN_INDEX = 1;

    private EventCallback<Set<String>> onDeleteAction;
    private String systemId;
    private String layerTargetId;

    public EvaluationRequireSheetView(){
        this.getStyleClass().add("pes-sheet-view");
        var grid = new GridBase(DEFAULT_EMPTY_DATA_COUNT, COLUMNS.size());
        grid.getColumnHeaders().addAll(COLUMNS);
        buildGrid(grid,DEFAULT_EMPTY_DATA_COUNT);
        setGrid(grid);
        getColumns().get(PROJECT_COLUMN_INDEX).setPrefWidth(400);
        getColumns().get(DESC_COLUMN_INDEX).setPrefWidth(500);
        //this.setRequiredColumns();
    }

    public String getLayerTargetId(){
        return this.layerTargetId;
    }

    public void setLayerTargetId(String layerTargetId){
        this.layerTargetId = layerTargetId;
    }

    public void initialize(String systemId,EventCallback<Set<String>> deleteAction){
        this.systemId = systemId;
        this.onDeleteAction = deleteAction;
        this.editModel.set(false);
    }

    @Override
    protected void loadContent(EvaluationRequireVO info,Integer sheetRowIndex){
        this.checkAndAppendEmptyDataRow(sheetRowIndex);
        this.getGrid().getRows().get(sheetRowIndex).get(PROJECT_COLUMN_INDEX).setItem(autoLine(info.getProject()));
        this.getGrid().getRows().get(sheetRowIndex).get(DESC_COLUMN_INDEX).setItem(autoLine(info.getRequire()));
        info.resetChange();
    }

    public List<EvaluationRequireVO> getModifyData(){
        List<EvaluationRequireVO> data = new ArrayList<>();
        for(var sheetRowIndex=0;sheetRowIndex<this.getGrid().getRows().size();sheetRowIndex++){
            if(this.isEmptyData(sheetRowIndex)){
                continue;
            }
            data.add(getModifyData(sheetRowIndex));
        }
        return data.stream()
                .filter(item-> Objects.nonNull(item) && item.isChange())
                .collect(Collectors.toList());
    }

    private EvaluationRequireVO getModifyData(Integer sheetRowIndex){
        if(toDataIndex(sheetRowIndex)<0){
            return null;
        }
        var rowData = this.getGrid().getRows().get(sheetRowIndex);
        EvaluationRequireVO info;
        if(toDataIndex(sheetRowIndex)<this.sheetData.size()){
            info = this.sheetData.get(toDataIndex(sheetRowIndex));
        }else{
            info = new EvaluationRequireVO();
            info.setSystemId(this.systemId);
            info.setLayerTargetId(this.layerTargetId);
        }
        info.setProject(rowData.get(PROJECT_COLUMN_INDEX).getText());
        info.setRequire(rowData.get(DESC_COLUMN_INDEX).getText());
        return info;
    }

    @Override
    protected boolean validate(ObservableList<SpreadsheetCell> rowData){
        boolean validResult = true;
        if(StringUtils.isBlank(rowData.get(PROJECT_COLUMN_INDEX).getText())){
            rowData.get(PROJECT_COLUMN_INDEX).getStyleClass().add(REQUIRED_CELL_STYLE);
            validResult = false;
        }else{
            rowData.get(PROJECT_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
        }
        return validResult;
    }

    @Override
    protected void clearValidate(ObservableList<SpreadsheetCell> rowData) {
        rowData.get(PROJECT_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
    }

    @Override
    protected boolean isEmptyData(Integer sheetRowIndex){
        if(toDataIndex(sheetRowIndex) < 0){
            return true;
        } else if(toDataIndex(sheetRowIndex) < this.sheetData.size()){
            return false;
        }
        var rowData = this.getGrid().getRows().get(sheetRowIndex);
        return StringUtils.isBlank(rowData.get(PROJECT_COLUMN_INDEX).getText())
                && StringUtils.isBlank(rowData.get(DESC_COLUMN_INDEX).getText());
    }

    private String autoLine(String content){
        if(StringUtils.isBlank(content)){
            return content;
        }
        return StringUtils.replace(content,"\\n","\n");
    }

    @Override
    protected ObservableList<SpreadsheetCell> generateEmptyDataRow(int dataIndex) {
        final ObservableList<SpreadsheetCell> data = FXCollections.observableArrayList();
        AtomicInteger columnIndex = new AtomicInteger(0);
        data.add(getTextAreaCell(toSheetRowIndex(dataIndex),columnIndex.getAndIncrement()));
        data.add(getTextAreaCell(toSheetRowIndex(dataIndex),columnIndex.getAndIncrement(),"data-cell-left"));
        return data;
    }

    @Override
    protected void deleteData() {
        if(Objects.nonNull(this.onDeleteAction)){
            var selectIds= this.selectedSheetRowIndex()
                    .stream()
                    .filter(sheetRowIndex->toDataIndex(sheetRowIndex)>=0 && toDataIndex(sheetRowIndex)<this.sheetData.size())
                    .map(sheetRowIndex->this.sheetData.get(toDataIndex(sheetRowIndex)).getId())
                    .collect(Collectors.toSet());
            this.onDeleteAction.action(selectIds);
        }
    }

    @Override
    protected List<String> getDataColumns() {
        return COLUMNS;
    }

    private void setRequiredColumns(){
        this.setCornerTag(this.getGrid().getRows().get(0).get(PROJECT_COLUMN_INDEX));
    }

}